package com.dao.implement;

import com.dao.UserDao;
import com.model.User;
import com.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Wray
 */
public class UserDaoImpl implements UserDao {


    @Override
    /**
     *
     */
    public User selectByUsername(String username) {
        String sql = "select * from users where username=?;";
        User user = null;

        try (Connection conn = JdbcUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql);) {

            pstmt.setString(1, username);
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()) {
                user = new User(rs.getString("username"), rs.getString("nickname"), rs.getString("password"));
            }
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public Boolean register(String username,String password) {
        String sql="insert into users(username,nickname,password) values(?,?,?);";
        Boolean flag=false;
        String defaultName="用户";
        try (Connection conn = JdbcUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)){
            pstmt.setString(1,username);
            pstmt.setString(2,defaultName);
            pstmt.setString(3,password);
            flag=(pstmt.executeUpdate()!=0);
        }catch (SQLException e){
                e.printStackTrace();
            }

        return flag;
    }


    /**
     * 销户
     *
     * @param username
     */
    @Override
    public Boolean delete(String username) {
        String sql = "delete from users where username=?;";
        int rs = 0;
        try (Connection conn = JdbcUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            rs = pstmt.executeUpdate();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
        return (rs != 0);
    }

    @Override
    public Boolean update(User user) {
        String sql="update users set nickname=?, password=? where username=?";
        int rs = 0;
        try (Connection conn = JdbcUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getNickname());
            pstmt.setString(2,user.getPassword());
            pstmt.setString(3,user.getUsername());
            rs = pstmt.executeUpdate();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
        return (rs != 0);
    }




}
